package cn.miao.test.direct;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @program: QuickStart-RabbitMQ
 * @description: 消费者
 * @author: MiaoWei
 * @create: 2021-10-19 18:28
 **/
public class Consumer1 {

    private static final String DIRECT_QUEUE_1 = "direct_queue1";

    public static void main(String[] args) throws Exception {
        //1.创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");

        //2.创建连接Connection
        Connection connection = connectionFactory.newConnection("生成者");
        //3.通过连接获取通道channel
        Channel channel = connection.createChannel();

        //创建队列
        channel.queueDeclare(DIRECT_QUEUE_1, true, false, false, null);
        //和交换机进行绑定
        channel.queueBind(DIRECT_QUEUE_1, "direct_ex", "info");


        //4.监听指定队列接收消息
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            //envelope:信封
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumerTag = " + consumerTag);
                System.out.println("获取交换机 = " + envelope.getExchange());
                System.out.println("获取路由key = " + envelope.getRoutingKey());
                System.out.println("获取消息的id = " + envelope.getDeliveryTag());
//                System.out.println("获取其他属性 = " + properties.getHeaders());
                System.out.println("获取消息主体 = " + new String(body));
                //手动应答
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(DIRECT_QUEUE_1, false, consumer);
        System.out.println("开始接收消息");
        //这里我不让程序往下执行,进行阻断
        System.in.read();
    }
}
